//
//  UIView+GestureBlock.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/26.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "UIView+GestureBlock.h"

#import <objc/runtime.h>

static const char *GestureBlockKey;

@implementation UIView (GestureBlock)
- (__kindof UIGestureRecognizer *)addGestureRecognizer:(GestureType)type block:(GestureBlock)block {
    if (block) {
        NSDictionary *dic = @{@"0":@"UITapGestureRecognizer",
                              @"1":@"UILongPressGestureRecognizer",
                              @"2":@"UISwipeGestureRecognizer",
                              @"3":@"UIPanGestureRecognizer",
                              @"4":@"UIRotationGestureRecognizer",
                              @"5":@"UIPinchGestureRecognizer"};
        
        NSString *string = dic[@(type).stringValue];
        UIGestureRecognizer *gesture = [[NSClassFromString(string) alloc] initWithTarget:self action:@selector(gestureAction:)];
        [self addGestureRecognizer:gesture];
        
        NSMutableDictionary *blockDic = objc_getAssociatedObject(self, GestureBlockKey);
        if (!blockDic) {
            blockDic = @{}.mutableCopy;
            objc_setAssociatedObject(self, GestureBlockKey, blockDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        [blockDic setObject:block forKey:string];
    
        return gesture;
    }
    return nil;
}

- (void)gestureAction:(UIGestureRecognizer *)gesture {
    NSMutableDictionary *blockDic = objc_getAssociatedObject(gesture.view, GestureBlockKey);
    GestureBlock block = blockDic[NSStringFromClass([gesture class])];
    
    if (block) {
        block(gesture.view, gesture);
    }
}
@end
